/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-05 10:11:57
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-05 17:09:30
 */
import React, { useEffect, useState, useRef } from 'react'
import Icon from '@/components/Icon/Icon'
import { NavBar, Input, List } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useInitialState } from '@/hooks/useInitialState'

import { getUserAction } from '@/store/actions/profile'

/* websocket */
import io, { Socket } from 'socket.io-client'
import { getToken } from '@/utils/storage'


const Chat = () => {
  // 用于缓存 socket.io 客户端实例
  const clientRef = useRef<Socket | null>(null)
  const boxRef = useRef<HTMLDivElement | null>(null)
  const [message, setMessage] = useState('')
  const [messageList, setMessageList] = useState<
    {
      type: 'robot' | 'user'
      text: string
    }[]
  >([
    { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', text: '你好' },
    { type: 'user', text: '你好' }
  ])
  useEffect(() => {
    // 和服务器建立了链接
    const client = io('http://toutiao.itheima.net', {
      query: {
        token: getToken().token
      },
      transports: ['websocket']
    })

    // 监听连接成功的事件
    client.on('connect', () => {
      // 向聊天记录中添加一条消息
      setMessageList(messageList => [
        ...messageList,
        { type: 'robot', text: '我现在恭候着您的提问。' }
      ])
    })
    client.on('message', (msg) => {
      console.log(msg, 33);

      // 向聊天记录中添加一条消息
      setMessageList(messageList => [
        ...messageList,
        { type: 'robot', text: msg.msg }
      ])
    })

    clientRef.current = client

    return () => {
      client.close() // 断开连接
    }
  }, [])

  useEffect(() => {
    // 设置页面滚动高度
    const current = boxRef.current!
    current.scrollTop = current.scrollHeight


  }, [messageList])

  /* 发送 */
  const sendHandle = (e: any) => {

    // console.log(e);
    if (e.key === 'Enter') {
      // 发送数据退给服务器
      clientRef.current?.emit('message', { msg: message, timestamp: Date.now() })
      // 将数据展示到页面上
      setMessageList(messageList => [...messageList, { type: 'user', text: message }])
      // 清空表单
      setMessage('')
    }

  }


  const history = useHistory()


  /* 获取用户信息 */
  const { user } = useInitialState(getUserAction, 'profile')
  // console.log(res, 3);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={boxRef}>
        {/* 机器人的消息 */}
        {
          messageList.length > 1 && messageList.map((item, index) => {
            if (item.type === 'robot') {
              return <div className="chat-item" key={index}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.text}</div>
              </div>
            } else {
              {/* 用户的消息 */ }
              return <div className="chat-item user" key={index}>
                <img src={user.photo} alt="" />
                <div className="message">{item.text}</div>
              </div>
            }
          })
        }
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <List.Item
          className="login-code-extra"
          extra={<span className="code-extra" >发送</span>}>
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={message}
            onChange={e => setMessage(e)}
            onKeyUp={sendHandle}
          />
        </List.Item>

        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat